// import md5 from 'js-md5';
import $json from '../../JsonConfig';
const _shopId = '';
// #ifdef H5
// 微信公众号
const { authorizationStoragePre, redirect_uri, merberIdStorage } = $json.wxPublic;
import $wechat from '../wechat/wechat.js'
// #endif
//#ifdef APP-PLUS
const { authorizationStorageAppPre, shopIdApp } = $json.appPublic;
// #endif
const baseUrl = 'http://shopappapi.yy12365.com';

export default {
	config: {
		baseUrl: baseUrl,
		header: {
			'Content-Type': 'application/json;charset=UTF-8'
		},
		data: {},
		method: "POST",
		dataType: "json",
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: (res) => {
			let code = res.statusCode;
			if (code !== 200) {
				let url, userId, shopId,sign;
				
				// #ifdef H5
				var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				if (r === '' || r === null) {
					return;
				}
				 url = r[2].split('_')[0] + window.location.host;
				shopId = uni.getStorageSync(`SHOPID_` + url) || '';
				userId = uni.getStorageSync(`${authorizationStoragePre}` + url) || '';
				sign = "H5";
				// #endif
				
				//#ifdef APP-PLUS
				url = shopIdApp;
				shopId = shopIdApp || '';
				userId = uni.getStorageSync(`${authorizationStorageAppPre}` + url) || '';
				sign = "APP";
				// #endif 
				if (userId === '' && shopId !== '') {
					// #ifdef H5 
					// 微信公众号  // h5端没有授权去授权
					let shopAppId = uni.getStorageSync(`SHOPAPPID_` + url) || '';
					let _memberId = uni.getStorageSync(`${merberIdStorage}` + shopId) || '';
					if ($wechat && $wechat.isWechat()) {
						const encodeIndexUrl = encodeURIComponent(redirect_uri);
						location.href =
							`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${shopAppId}&redirect_uri=${encodeIndexUrl}&response_type=code&scope=snsapi_userinfo&state=${shopId}_${_memberId}_${shopAppId}#wechat_redirect`;
					}
					// #endif
					// app端没有授权时有什么特殊需求未知
				} else {
					if (code === 401 && userId !== '') { // 401 拦截，刷新sessionId
						uni.request({
							url: baseUrl + '/shopApp/wechat/autoLogin',
							method: 'GET',
							header: {
								'Content-Type': 'application/json;charset=UTF-8'
							},
							data: {
								userId: userId,
								shopId: shopId,
								sign: sign
							},
							success: (res) => {
								console.log(res, 'userId: ', userId, 'shopId: ', shopId);
								if (res.data.data && res.data.data.sessionId) {
									// #ifdef H5
									uni.setStorageSync(`sessionId_` + url, res.data.data.sessionId);
									// #endif
									//#ifdef APP-PLUS
									uni.setStorageSync(`sessionId_` + url, res.data.data.sessionId);
									// #endif
								}
							}
						});
					}
				}
			}
		}
	},
	request(options = {}, needSession = true) {
		options.baseUrl = options.baseUrl || this.config.baseUrl;
		options.dataType = options.dataType || this.config.dataType;
		options.url = options.baseUrl + options.url;
		options.data = options.data || {};
		options.method = options.method || this.config.method;
		if (options.header && options.header['Content-Type']) {
			this.config.header['Content-Type'] = options.header['Content-Type'];
		}
		if (needSession) {
			let url;
			// #ifdef H5
			var reg = new RegExp("(^|&)state=([^&]*)(&|$)", "i");
			var r = window.location.search.substr(1).match(reg)[2];
		    url = r.split('_')[0] + window.location.host;
			 
			//#endif
			//#ifdef APP-PLUS
			url = shopIdApp;
			//#endif	 
			const _customSession = {
				'customsession': uni.getStorageSync(`sessionId_` + url)
			};
			options.header = Object.assign({}, this.config.header, _customSession);
		}
		return new Promise((resolve, reject) => {
			let _config = null;
			options.complete = (response) => {
				// console.log('response: ', response);
				let statusCode = response.statusCode;
				response.config = _config;
				if (process.env.NODE_ENV === 'development') {
					if (statusCode === 200) {
						// console.log("【" + _config.requestId + "】 结果：" + JSON.stringify(response.data))
					}
				}
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				// 统一的响应日志记录
				// _reslog(response)
				if (statusCode === 200 && response.data.success) { //成功
					resolve(response);
				} else {
					reject(response)
				}
				// 20210311 - 以下判断request成功后，返回data数据是对象则判断success是否是true-成功，不是对象判断只要返回结果不是null也认为是成功，但担心有以往接口回调处理不兼容，故未使用
				// let resData = response.data;
				// if (statusCode === 200) {
				// 	console.log(2, 200);
				// 	if (Object.prototype.toString.call(resData) === '[object Object]') { // 是不为null的对象
				// 		if (resData.success) {
				// 			resolve(response);
				// 		} else {
				// 			reject(response);
				// 		}
				// 	} else {
				// 		if (resData !== null) {
				// 			resolve(response);
				// 		} else {
				// 			reject(response);
				// 		}
				// 	}
				// } else {
				// 	reject(response);
				// }
			};
			_config = Object.assign({}, this.config, options);
			_config.requestId = new Date().getTime();
			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			// 统一的请求日志记录
			// _reqlog(_config)
			// alert(JSON.stringify(_config));
			uni.request(_config);
		});
	},

	get(url, data, options, needSession) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options, needSession)
	},
	post(url, data, options, needSession) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options, needSession)
	},
	put(url, data, options, needSession) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options, needSession)
	},
	delete(url, data, options, needSession) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options, needSession)
	},
};

/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + req.requestId + "】 地址：" + req.url)
		console.log("【" + req.requestId + "】 请求头：" + req.header)
		if (req.data) {
			console.log("【" + req.requestId + "】 请求参数：" + JSON.stringify(req.data))
		}
	}
	//TODO 调接口异步写入日志数据库
}
/**
 * 响应接口日志记录
 */
function _reslog(res) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		console.log("【" + res.config.requestId + "】 地址：" + res.config.url)
		console.log("【" + res.config.requestId + "】 请求头：" + res.header)
		if (res.config.data) {
			console.log("【" + res.config.requestId + "】 请求参数：" + JSON.stringify(res.config.data))
		}
		console.log("【" + res.config.requestId + "】 响应结果：" + JSON.stringify(res))
	}
	//TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库
	switch (_statusCode) {
		case 200:
			break;
		case 401:
			break;
		case 404:
			break;
		default:
			break;
	}
}
